<template>
    <div class="chooser">
        <span v-for="(item,index) in selections" :class="{on:checkActive(index)}" @click="toggleSelection(index)">{{item.label}}</span>
    </div>
</template>

<script>
export default {
    data() {
        return {
            nowIndexes: [0]
        }
    },
    props: {
        selections: {
            type: Array,
            default: [{
                label: 'test',
                value: 0
            }]
        }
    },
    methods: {
        toggleSelection(index) {

            // 判断nowIndexes里面有没有当前的值,如果有，则移除，没有就添加

            // 定义变量接收查找数组回来的值
            var result = this.indexOfArray(this.nowIndexes, index)

            if (result != -1) {
                // 移除数组
                this.nowIndexes.splice(result, 1);
            } else {
                //添加数组
                this.nowIndexes.push(index);
            }
            
            let objArray = [];
            for(let i=0;i<this.nowIndexes.length;i++){
                objArray.push(this.selections[this.nowIndexes[i]]);
            }



            this.$emit('on-change',objArray)
        },
        checkActive(index) {
            // 判断nowIndexes 的值与 传进来的值对面。如果有为true,否则为false
            return this.indexOfArray(this.nowIndexes, index) != -1;
        },
        // 查找数组
        indexOfArray(arr, val) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == val) return i;
            }
            return -1;
        }
    }
}
</script>

<style scoped>
.chooser span {
    padding: 5px 25px;
    border: 1px solid #e3e3e3;
    margin-right: 10px;
    text-align: center;
    cursor: pointer;

    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.chooser span.on {
    background: #4fc08d;
    color: #fff;
    border: 1px solid #4fc08d;
}
</style>
